<!-- 预订 - 桌台列表 - 组件（Vue3） -->
<template>
  <div>
    <div class="desk-top-content">
      <div class="paging-list-box">
        <div
          class="paging-list-item"
          :class="{ 'paging-list-item-active': pagingActiveIndex === pagingIndex }"
          @click="handleSelectPaging(pagingIndex, pagingItem.id)"
          v-for="(pagingItem, pagingIndex) in desktopCategoryList"
          :key="pagingItem.id"
        >
          <el-tooltip class="item" effect="dark" :content="pagingItem.name" placement="top">
            <div class="name">{{ pagingItem.name }}</div>
          </el-tooltip>
        </div>
        <div class="paging-list-btn">
          <img
            class="left-btn"
            @click="oneCatePreviousPage"
            src="@/assets/images/home/page-left-icon.png"
            alt=""
          />
          <img
            class="right-btn"
            @click="oneCateNextPage"
            src="@/assets/images/home/page-right-icon.png"
            alt=""
          />
        </div>
      </div>
      <div class="tag-status-wrap">
        <div class="tag-select-box">
          <div class="tag-btn-list">
            <div
              class="tag-btn-item"
              :class="{ 'tag-btn-item-active': tagActiveIndex === tagIndex }"
              @click="handleSelectTag(tagIndex, tagItem.status)"
              v-for="(tagItem, tagIndex) in tagButtonList"
              :key="tagItem.name + tagIndex"
            >
              {{ tagItem.name }}
            </div>
          </div>
        </div>
        <div class="status-box">
          <div class="status-item">
            <div class="circular"></div>
            <div class="desc">空闲</div>
          </div>
          <div class="status-item">
            <div class="circular"></div>
            <div class="desc">在用</div>
          </div>
          <div class="status-item">
            <div class="circular"></div>
            <div class="desc">预订</div>
          </div>
        </div>
      </div>
      <!-- 滚动列表 -->
      <div class="desktop-scroll-list" v-loading="listLoading">
        <div class="scroll-list-item-content" v-if="deskTopList && deskTopList.length">
          <div
            class="scroll-list-item"
            v-for="(desk, index) in deskTopList"
            :key="desk.id + '-' + index"
            @click.stop="handleSelectTable(index, desk)"
            @dblclick.stop="handleDoubleSelect(index, desk)"
            :style="{
              'border-color':
                desk.is_use && desk.is_use.value === 1 && desk.status && desk.status.value === 1
                  ? deskOrderStatus[desk.status && desk.status.value ? desk.status.value : '']
                  : deskUseStatus[desk.is_use && desk.is_use.value ? desk.is_use.value : '']
            }"
          >
            <div
              class="title-box"
              :style="{
                background:
                  desk.is_use && desk.is_use.value === 1 && desk.status && desk.status.value === 1
                    ? deskOrderStatus[desk.status && desk.status.value ? desk.status.value : '']
                    : deskUseStatus[desk.is_use && desk.is_use.value ? desk.is_use.value : '']
              }"
            >
              <div class="name-box">
                <div
                  class="name"
                  v-if="
                    desk.is_use && desk.is_use.value === 1 && desk.status && desk.status.value === 1
                  "
                >
                  {{ deskStatusText[desk.status && desk.status.value ? desk.status.value : ''] }}
                </div>
                <div class="name" v-else>
                  <span v-if="desk.is_use && desk.is_use.text">{{ desk.is_use.text }}</span>
                </div>
                <img
                  class="lock-icon"
                  v-if="desk.is_lock && desk.is_lock.value === 1"
                  src="@/assets/images/home/lock-icon.png"
                  alt=""
                />
              </div>
              <div class="count">
                <span>{{ desk.use_num || '0' }}</span
                >/<span>{{ desk.capacity }}人</span>
              </div>
            </div>
            <div class="desc-box">
              <div class="name">{{ desk.name }}</div>
              <template v-if="!isEmpty(desk && desk.bookInfo)">
                <div class="price mb-8">定金：￥{{ desk.bookInfo.book_money || 0 }}</div>
                <div class="user mb-8">预订人：{{ desk.bookInfo.user_name }}</div>
                <div class="phone mb-8">电话：{{ desk.bookInfo.mobile }}</div>
                <div class="time">
                  <div>预留{{ desk.bookInfo.keep_time }}分钟</div>
                </div>
              </template>
            </div>
          </div>
          <!-- 占位元素，纯样式 -->
          <div
            class="scroll-list-item-zhanwei"
            v-for="val in ['val1', 'val2', 'val3', 'val4']"
            :key="val"
          ></div>
        </div>

        <!-- 暂无数据 -->
        <div class="no-data-box" v-else>
          <NotData desc="暂无桌台数据" />
        </div>
      </div>
    </div>
    <div class="desktop-count-box">
      <div class="left">共{{ pageTotal }}条</div>
      <div class="right">
        <Pagination
          v-if="pageTotal > 0"
          :total="pageTotal"
          v-model:page="deskListPageParams.page"
          v-model:limit="deskListPageParams.limit"
          @pagination="getBookDeskTopList"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, defineEmits, defineProps, onMounted } from 'vue'
import NotData from '@/components/NotData/Index.vue'
import Pagination from '@/components/Pagination/Index.vue'
import { DESK_USE_STATUS, DESK_ORDER_STATUS, DESK_STATUS_TEXT } from '@/constants/desktopStatus'
import { isEmpty, filterObjectEmptyAttribute, dealAssignDataFunction } from '@/utils/toolsValidate'
import { bookDeskTopList } from '@/api/book'
import { fetchCategoryList } from '@/api/desktop'
import { getNowDateAndTime } from '@/utils/index'

interface CategoryItem {
  id: number | string
  name: string
}
interface DeskItem {
  id: number | string
  name: string
  capacity?: number
  use_num?: number
  is_use?: { value: number; text?: string }
  status?: { value: number }
  is_lock?: { value: number }
  bookInfo?: any
}

// 接收父组件的基础过滤条件（日期/班次/桌台号）
const props = defineProps<{ filters?: { day?: string; time_slot?: string; name?: string } }>()

const emit = defineEmits<{ (e: 'onDoubleSelect', desk: DeskItem): void }>()

// 本地状态（供父组件通过 ref 重置）
const pagingActiveIndex = ref<number>(0)
const tagActiveIndex = ref<number>(0)
const selectTableActiveIndex = ref<number>(-1)

// 旧项目按钮与颜色映射
const deskUseStatus = DESK_USE_STATUS as Record<string | number, string>
const deskOrderStatus = DESK_ORDER_STATUS as Record<string | number, string>
const deskStatusText = DESK_STATUS_TEXT as Record<string | number, string>

// 标签按钮列表
const tagButtonList = ref([
  { name: '全部', status: 0 },
  { name: '空闲', status: 1 },
  { name: '在用', status: 2 },
  { name: '预订', status: 3 }
])

// 数据源与分页分类（内部维护）
const desktopCategoryList = ref<CategoryItem[]>([])
const deskTopList = ref<DeskItem[]>([])
const pageTotal = ref<number>(0)
const listLoading = ref<boolean>(false)

// 列表查询参数（内部维护）
const deskListPageParams = ref({
  page: 1,
  limit: 10,
  name: '',
  status: 0,
  day: '',
  time_slot: 'all',
  category_id: '' as string | number | ''
})

// 分类分页（内部维护）
const deskCategoryPageQuery = ref({ page: 1, limit: 5 })
const deskOneCategoryLastPage = ref(0)

// 监听父级过滤条件变化（仅在值实际变化时请求）
const lastFilterSignature = ref<string>('')
// 初始化默认查询条件
// 监听父级过滤条件变化
watch(
  () => props.filters,
  v => {
    const nextSig = `${v?.name || ''}|${v?.time_slot || 'all'}|${v?.day || ''}`
    if (nextSig === lastFilterSignature.value) return
    lastFilterSignature.value = nextSig

    deskListPageParams.value.name = v?.name || ''
    deskListPageParams.value.time_slot = v?.time_slot || 'all'
    if (v?.day) {
      deskListPageParams.value.day = v.day
    } else {
      const { currentNowDate } = getNowDateAndTime()
      deskListPageParams.value.day = currentNowDate
    }
    deskListPageParams.value.page = 1
    getBookDeskTopList()
  },
  { deep: true, immediate: true }
)

onMounted(() => {
  // 若父级未传 filters，组件自行初始化
  if (!props.filters || (!props.filters.day && !props.filters.time_slot && !props.filters.name)) {
    const { currentNowDate } = getNowDateAndTime()
    deskListPageParams.value.day = currentNowDate
    initLoad()
  } else {
    initLoad()
  }
})

// methods
function handleSelectPaging(index: number, id?: string | number) {
  pagingActiveIndex.value = index
  const categoryId = id || ''
  tagActiveIndex.value = 0
  deskListPageParams.value.page = 1
  deskListPageParams.value.category_id = categoryId
  deskListPageParams.value.status = 0
  getBookDeskTopList()
  selectTableActiveIndex.value = -1
}

function handleSelectTag(index: number, status: number) {
  tagActiveIndex.value = index
  deskListPageParams.value.page = 1
  deskListPageParams.value.status = status
  getBookDeskTopList()
  selectTableActiveIndex.value = -1
}

function handleSelectTable(index: number, item: DeskItem) {
  // 已预订不可新增
  if (item?.is_use?.value === 2) return
  selectTableActiveIndex.value = index
}

function handleDoubleSelect(index: number, item: DeskItem) {
  if (item?.is_use?.value === 2) return
  selectTableActiveIndex.value = index
  // 由父组件决定如何打开新增预订弹窗
  emit('onDoubleSelect', item)
}

function oneCatePreviousPage() {
  if (deskCategoryPageQuery.value.page === 1) {
    pagingActiveIndex.value = 0
    return
  }
  pagingActiveIndex.value = -1
  selectTableActiveIndex.value = -1
  deskCategoryPageQuery.value.page -= 1
  resetOneCate()
  getDesktopCategoryList()
}

function oneCateNextPage() {
  if (deskCategoryPageQuery.value.page >= deskOneCategoryLastPage.value) return
  pagingActiveIndex.value = -1
  selectTableActiveIndex.value = -1
  deskCategoryPageQuery.value.page += 1
  resetOneCate()
  getDesktopCategoryList()
}

// 数据获取
function getBookDeskTopList() {
  if (!deskListPageParams.value.day) {
    const { currentNowDate } = getNowDateAndTime()
    deskListPageParams.value.day = currentNowDate
  }
  listLoading.value = true
  bookDeskTopList(filterObjectEmptyAttribute(deskListPageParams.value))
    .then((res: any) => {
      if (res?.status === 200) {
        deskTopList.value = dealAssignDataFunction([], res?.data?.list?.data)
        pageTotal.value = Number(res?.data?.list?.total) || 0
      }
    })
    .finally(() => {
      listLoading.value = false
    })
}

function getDesktopCategoryList() {
  fetchCategoryList(deskCategoryPageQuery.value).then((res: any) => {
    if (res?.status === 200) {
      const list = isEmpty(res?.data?.data) ? [] : res.data.data
      desktopCategoryList.value = [{ id: 0, name: '全部' }, ...list]
      deskOneCategoryLastPage.value = isEmpty(res?.data?.last_page) ? 0 : res.data.last_page
    }
  })
}

function resetOneCate() {
  deskListPageParams.value.page = 1
  deskListPageParams.value.category_id = ''
  deskListPageParams.value.status = 0
  getBookDeskTopList()
}

function resetAll() {
  pagingActiveIndex.value = 0
  tagActiveIndex.value = 0
  selectTableActiveIndex.value = -1
  deskCategoryPageQuery.value = { page: 1, limit: 5 }
  deskListPageParams.value = {
    page: 1,
    limit: 10,
    name: props.queryParams?.name || '',
    status: 0,
    day: props.queryParams?.day || '',
    time_slot: props.queryParams?.time_slot || 'all',
    category_id: ''
  }
  getDesktopCategoryList()
  getBookDeskTopList()
}

function initLoad() {
  getDesktopCategoryList()
  getBookDeskTopList()
}

// no expose
</script>

<style lang="scss" scoped>
.desk-top-content {
  // width: 1104px;
  background: #f4f4f4;
  box-sizing: border-box;
  padding: 20px 0px;
  height: 676px; // 固定高度，防止内容溢出
  display: flex;
  flex-direction: column;
  overflow: hidden;
  .paging-list-box {
    position: relative;
    box-sizing: border-box;
    width: 946px;
    height: 48px;
    margin: 0 30px;
    background: #ffffff;
    border: 1px solid #d0d0d0;
    border-radius: 25px;
    display: flex;
    align-items: center;
    .paging-list-item {
      display: inline-block;
      padding: 0 38px;
      height: 48px;
      line-height: 48px;
      font-size: 16px;
      font-family:
        PingFang SC,
        PingFang SC-Regular;
      font-weight: 400;
      text-align: center;
      color: #333333;
      cursor: pointer;
      .name {
        max-width: 100px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
    .paging-list-item-active {
      color: #ffffff;
      background: #7c0a03;
      border-radius: 24px;
    }
    .paging-list-btn {
      position: absolute;
      top: 12px;
      right: 16px;
      display: flex;
      align-items: center;
      .left-btn,
      .right-btn {
        flex-shrink: 0;
        width: 24px;
        height: 24px;
        cursor: pointer;
      }
      .left-btn {
        margin-right: 20px;
      }
    }
  }
  .tag-status-wrap {
    display: flex;
    align-items: center;
    margin: 0 30px;
    margin-top: 20px;

    .tag-select-box {
      display: flex;
      align-items: center;
      .tag-btn-list {
        display: flex;
        align-items: center;
        .tag-btn-item {
          min-width: 96px;
          height: 40px;
          line-height: 40px;
          border: 1px solid #d2d2d2;
          border-radius: 12px;
          font-size: 16px;
          font-family:
            PingFang SC,
            PingFang SC-Regular;
          font-weight: 400;
          text-align: center;
          color: #666666;
          cursor: pointer;
          margin-right: 24px;
          background: #fff;
        }
        .tag-btn-item:last-child {
          margin-right: 0;
        }
        .tag-btn-item-active {
          border-color: #7c0a03 !important;
          color: #7c0a03 !important;
        }
      }
    }
    .status-box {
      display: flex;
      align-items: center;
      margin-left: 80px;
      .status-item {
        display: flex;
        align-items: center;
        margin-right: 30px;
        .circular {
          margin-right: 12px;
          width: 16px;
          height: 16px;
          background: #efb176;
          border-radius: 50%;
        }
        .name {
          font-size: 16px;
          font-family:
            PingFang SC,
            PingFang SC-Regular;
          font-weight: 400;
          color: #efb176;
        }
      }
      .status-item:first-child {
        .circular {
          background: #999999;
        }
        .name {
          color: #999999;
        }
      }
      .status-item:nth-child(2) {
        .circular {
          background: #7a8972;
        }
        .name {
          color: #7a8972;
        }
      }
      .status-item:last-child {
        margin-right: 0;
      }
    }
  }
  .desktop-scroll-list {
    box-sizing: border-box;
    flex: 1;
    overflow-y: auto;
    .scroll-list-item-content {
      display: flex;
      align-items: center;
      padding: 0 30px;
      flex-wrap: wrap;
      justify-content: space-between;
      .scroll-list-item {
        position: relative;
        width: 215px;
        height: 210px;
        box-sizing: border-box;
        background: #ffffff;
        border: 1px solid #d2d2d2;
        border-top: none;
        border-radius: 12px;
        margin-top: 20px;
        .title-box {
          display: flex;
          align-items: center;
          justify-content: space-between;
          height: 44px;
          background: #d2d2d2;
          padding: 0 12px;
          font-size: 14px;
          font-family:
            PingFang SC,
            PingFang SC-Bold;
          font-weight: 700;
          color: #ffffff;
          border-radius: 12px 12px 0px 0px;
        }
        .desc-box {
          padding: 10px 0 0 12px;
          font-size: 14px;
          font-family:
            PingFang SC,
            PingFang SC-Regular;
          font-weight: 400;
          text-align: left;
          color: #333333;
          .name {
            font-size: 36px;
            font-family:
              PingFang SC,
              PingFang SC-Bold;
            font-weight: 700;
            text-align: left;
            color: #434447;
            margin-bottom: 20px;
            margin-top: 10px;
          }
          .time {
            display: flex;
            align-items: center;
            font-size: 14px;
            font-family:
              PingFang SC,
              PingFang SC-Regular;
            font-weight: 400;
            color: #333333;
            > div {
              margin-right: 10px;
            }
          }
        }
      }
    }
    .choose-img {
      position: absolute;
      right: 12px;
      bottom: 12px;
      width: 24px;
      height: 24px;
    }
  }
  .scroll-list-item-zhanwei {
    width: 215px;
    overflow: hidden;
  }
}
.desc {
  font-size: 14px;
  font-family:
    PingFang SC,
    PingFang SC-Regular;
  font-weight: 400;
  color: #333333;
}
.desk-top-content::-webkit-scrollbar {
  width: 6px !important;
  height: 0 !important;
}
.desk-top-content::-webkit-scrollbar-thumb {
  height: 200px !important;
  background: #d2d2d2 !important;
  border-radius: 3px !important;
}
.desk-top-content::-webkit-scrollbar-track {
  display: none !important;
}
.no-data-box {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 170px;
  margin-top: 250px;
}
.mb-8 {
  margin-bottom: 8px;
}
.desktop-count-box {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  .left {
    font-size: 14px;
    font-family:
      PingFang SC,
      PingFang SC-Regular;
    font-weight: 400;
    color: #333333;
  }
}
</style>
